<?php

namespace Core\Forms\Element;

use Phalcon\Di;

class Chosen extends Select
{
    protected $_chosenSource;

    public function __construct($name, $options = null, $attributes = null)
    {
        parent::__construct($name, $options, $attributes);
        $this->_chosenSource = Di::getDefault()->getShared('config')->cache('chosenSource');
    }

    public function setDefault($value)
    {
        if ($value && isset($this->_chosenSource[$this->_options['chosenSource']['handle']])) {
            $chosenSource = $this->_chosenSource[$this->_options['chosenSource']['handle']];
            $chosenSourceClass = $chosenSource['class'] . '::getOptions';
            if(isCallable($chosenSourceClass)) {
                $options = call_user_func($chosenSourceClass, $value);
                $this->setOptions($options);
            }
        }
        return parent::setDefault($value);
    }

    public function render($attributes = null)
    {
        $di = Di::getDefault();
        $source = '';
        if (isset($this->_chosenSource[$this->_options['chosenSource']['handle']])) {
            $chosenSourceHandle = $this->_options['chosenSource']['handle'];
            if (!isset($this->_options['chosenSource']['args'])) {
                $this->_options['chosenSource']['args'] = [];
            }
            $source = $di->getShared('url')->get(['for' => 'chosenSource', 'id' => $chosenSourceHandle], $this->_options['chosenSource']['args']);
        }

        $script =
<<<scription
    $("#{$this->_name}").ajaxChosen({
        type: 'GET',
        url: '{$source}',
        dataType: 'json'
    }, function(json) {
        var results = [];
        $.each(json.items, function(i, val) {
            results.push({
                id: val.id,
                name: val.name
            });
        });
        return results;
    });
scription;

        $di->getShared('assets')
            ->addJs('chosen', '//cdn.bootcss.com/chosen/1.6.2/chosen.jquery.min.js', 'footer')
            ->addJs('ajax-chosen', '/library/chosen-ajax-addition/ajax-chosen.js', 'footer')
            ->addCss('chosen', '//cdn.bootcss.com/chosen/1.6.2/chosen.min.css', 'footer')
            ->addInlineJs('chosen-init-' . $this->_name, $script, 'footer');

        return parent::render($attributes);
    }
}
